<?php
/**
 * Created by PhpStorm.
 * User: Duanwangye
 * Date: 18/09/21
 * Company:财联集惠
 */

namespace tool;

class Common
{
    public static function rm($code = 0, $msg = '操作成功', $content = '') {

        $res = [];
        if(is_array($content) || $content) {
            $res['code'] = $code;
            $res['msg'] = $msg;
            $res['content'] = $content;
            return $res;
        }
        else {
            $res['code'] = $code;
            $res['msg'] = $msg;
            return $res;
        }
    }

    public static function rj($code = 0, $msg = '', $content = '', $forward = '') {
        $result = Common::rm($code, $msg, $content);
        if($forward) {
            $result['forward'] = $forward;
        }
        return $result;
    }

    public static function timetodate($time = 0, $type = 6) {
        if(!$time) $time = THINK_START_TIME;
        $types = array('Y-m-d', 'Y', 'm-d', 'Y-m-d', 'm-d H:i', 'Y-m-d H:i', 'Y-m-d H:i:s', 'H:i', 'Y年m月d日 H点i分s秒', 'm月d日 H点i分', 'YmdHis', 'Ymd');
        if(isset($types[$type])) $type = $types[$type];
        $date = '';
        if($time > 2147212800) {
            if(class_exists('DateTime')) {
                $D = new DateTime('@'.($time - 3600 * intval(str_replace('Etc/GMT', '', $GLOBALS['CFG']['timezone']))));
                $date = $D->format($type);
            }
        }
        return $date ? $date : date($type, $time);
    }

    public static function second_array_unique_bykey($arr, $key)
    {
        $tmp_arr = array();
        foreach ($arr as $k => $v) {
            if (in_array($v[$key], $tmp_arr))   //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            {
                unset($arr[$k]); //销毁一个变量  如果$tmp_arr中已存在相同的值就删除该值
            } else {
                $tmp_arr[$k] = $v[$key];  //将不同的值放在该数组中保存
            }
        }
        //ksort($arr); //ksort函数对数组进行排序(保留原键值key)  sort为不保留key值
        $result = [];
        foreach ($arr as $k => $v) {
            $result[] = $v;
        }
        return $result;
    }


    public static function datetotime($date) {
        $time = strtotime($date);
        if($time === false) {
            if(class_exists('DateTime')) {
                $D = new DateTime($date);
                $time = $D->format('U');
            }
        }
        return $time;
    }


    public static function mdate($time = NULL) {
        $text = '';
        $time = $time === NULL || $time > time() ? time() : intval($time);
        $t = time() - $time; //时间差 （秒）
        $y = date('Y', $time)-date('Y', time());//是否跨年
        switch($t){
            case $t == 0:
                $text = '刚刚';
                break;
            case $t < 60:
                $text = $t . '秒前'; // 一分钟内
                break;
            case $t < 60 * 60:
                $text = floor($t / 60) . '分钟前'; //一小时内
                break;
            case $t < 60 * 60 * 24:
                $text = floor($t / (60 * 60)) . '小时前'; // 一天内
                break;
            case $t < 60 * 60 * 24 * 3:
                $text = floor($time/(60*60*24)) ==1 ?'昨天 ' . date('H:i', $time) : '前天 ' . date('H:i', $time) ; //昨天和前天
                break;
            case $t < 60 * 60 * 24 * 30:
                $text = date('m月d日 H:i', $time); //一个月内
                break;
            case $t < 60 * 60 * 24 * 365&&$y==0:
                $text = date('m月d日', $time); //一年内
                break;
            default:
                $text = date('Y年m月d日', $time); //一年以前
                break;
        }

        return $text;
    }


    public static function array_column($input, $columnKey, $indexKey = NULL)
    {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? TRUE : FALSE;
        $indexKeyIsNull = (is_null($indexKey)) ? TRUE : FALSE;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? TRUE : FALSE;
        $result = array();

        foreach ((array)$input AS $key => $row)
        {
            if ($columnKeyIsNumber)
            {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : NULL;
            }
            else
            {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : NULL;
            }
            if ( ! $indexKeyIsNull)
            {
                if ($indexKeyIsNumber)
                {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && ! empty($key)) ? current($key) : NULL;
                    $key = is_null($key) ? 0 : $key;
                }
                else
                {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }

            $result[$key] = $tmp;
        }

        return $result;
    }


    public static function get_client_ip($type = 0,$adv=false) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if($adv){
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos    =   array_search('unknown',$arr);
                if(false !== $pos) unset($arr[$pos]);
                $ip     =   trim($arr[0]);
            }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip     =   $_SERVER['HTTP_CLIENT_IP'];
            }elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip     =   $_SERVER['REMOTE_ADDR'];
            }
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }



    //获取客户端浏览器版本方法
    public static function get_client_browser(){
        $user_OSagent = $_SERVER['HTTP_USER_AGENT'];
        if(strpos($user_OSagent,"Maxthon") && strpos($user_OSagent,"MSIE")) {
            $visitor_browser ="Maxthon(Microsoft IE)";
        }elseif(strpos($user_OSagent,"Maxthon 2.0")) {
            $visitor_browser ="Maxthon 2.0";
        }elseif(strpos($user_OSagent,"Maxthon")) {
            $visitor_browser ="Maxthon";
        }elseif(strpos($user_OSagent,"rv:11.0")) {
            $visitor_browser ="MSIE 11.0";
        }elseif(strpos($user_OSagent,"MSIE 9.0")) {
            $visitor_browser ="MSIE 9.0";
        }elseif(strpos($user_OSagent,"MSIE 8.0")) {
            $visitor_browser ="MSIE 8.0";
        }elseif(strpos($user_OSagent,"MSIE 7.0")) {
            $visitor_browser ="MSIE 7.0";
        }elseif(strpos($user_OSagent,"MSIE 6.0")) {
            $visitor_browser ="MSIE 6.0";
        } elseif(strpos($user_OSagent,"MSIE 5.5")) {
            $visitor_browser ="MSIE 5.5";
        } elseif(strpos($user_OSagent,"MSIE 5.0")) {
            $visitor_browser ="MSIE 5.0";
        } elseif(strpos($user_OSagent,"MSIE 4.01")) {
            $visitor_browser ="MSIE 4.01";
        }elseif(strpos($user_OSagent,"MSIE")) {
            $visitor_browser ="MSIE 较高版本";
        }elseif(strpos($user_OSagent,"NetCaptor")) {
            $visitor_browser ="NetCaptor";
        } elseif(strpos($user_OSagent,"Netscape")) {
            $visitor_browser ="Netscape";
        }elseif(strpos($user_OSagent,"Chrome")) {
            $visitor_browser ="Chrome";
        } elseif(strpos($user_OSagent,"Lynx")) {
            $visitor_browser ="Lynx";
        } elseif(strpos($user_OSagent,"Opera")) {
            $visitor_browser ="Opera";
        } elseif(strpos($user_OSagent,"Konqueror")) {
            $visitor_browser ="Konqueror";
        } elseif(strpos($user_OSagent,"Mozilla/5.0")) {
            $visitor_browser ="Mozilla";
        } elseif(strpos($user_OSagent,"Firefox")) {
            $visitor_browser ="Firefox";
        }elseif(strpos($user_OSagent,"U")) {
            $visitor_browser ="Firefox";
        } else {
            $visitor_browser ="other";
        }

        if(!strpos($visitor_browser,"MSIE"))
        {
            if (preg_match('/FireFox\/(\d+)\..*/i', $user_OSagent, $regs))
                $visitor_browser=$visitor_browser." ".$regs[1];
            elseif (preg_match('/Opera[\s|\/](\d+)\..*/i', $user_OSagent, $regs))
                $visitor_browser=$visitor_browser." ".$regs[1];
            elseif (preg_match('/Chrome\/(\d+)\..*/i', $user_OSagent, $regs))
                $visitor_browser=$visitor_browser." ".$regs[1];
            elseif ((strpos($user_OSagent,'Chrome')==false)&&preg_match('/Safari\/(\d+)\..*$/i', $user_OSagent, $regs))
                $visitor_browser=$visitor_browser." ".$regs[1];
        }

        return $visitor_browser;
    }

    //获取客户端操作系统方法
    public static function get_client_os(){
        $user_OSagent = $_SERVER['HTTP_USER_AGENT'];
        if(strpos($user_OSagent,"NT 10.0")){
            $visitor_os ="Windows 10";
        } elseif(strpos($user_OSagent,"NT 6.4")){
            $visitor_os ="Windows 10";
        } elseif(strpos($user_OSagent,"NT 6.3")){
            $visitor_os ="Windows 8.1";
        } elseif(strpos($user_OSagent,"NT 6.2")){
            $visitor_os ="Windows 8";
        } elseif(strpos($user_OSagent,"NT 6.1")){
            $visitor_os ="Windows 7";
        } elseif(strpos($user_OSagent,"NT 5.1")) {
            $visitor_os ="Windows XP (SP2)";
        } elseif(strpos($user_OSagent,"NT 5.2") && strpos($user_OSagent,"WOW64")){
            $visitor_os ="Windows XP 64-bit Edition";
        } elseif(strpos($user_OSagent,"NT 5.2")) {
            $visitor_os ="Windows 2003";
        } elseif(strpos($user_OSagent,"NT 6.0")) {
            $visitor_os ="Windows Vista";
        } elseif(strpos($user_OSagent,"NT 5.0")) {
            $visitor_os ="Windows 2000";
        } elseif(strpos($user_OSagent,"4.9")) {
            $visitor_os ="Windows ME";
        } elseif(strpos($user_OSagent,"NT 4")) {
            $visitor_os ="Windows NT 4.0";
        } elseif(strpos($user_OSagent,"98")) {
            $visitor_os ="Windows 98";
        } elseif(strpos($user_OSagent,"95")) {
            $visitor_os ="Windows 95";
        }elseif(strpos($user_OSagent,"NT")) {
            $visitor_os ="Windows 较高版本";
        }elseif(strpos($user_OSagent,"Mac")) {
            $visitor_os ="Mac";
        } elseif(strpos($user_OSagent,"Linux")) {
            $visitor_os ="Linux";
        } elseif(strpos($user_OSagent,"Unix")) {
            $visitor_os ="Unix";
        } elseif(strpos($user_OSagent,"FreeBSD")) {
            $visitor_os ="FreeBSD";
        } elseif(strpos($user_OSagent,"SunOS")) {
            $visitor_os ="SunOS";
        } elseif(strpos($user_OSagent,"BeOS")) {
            $visitor_os ="BeOS";
        } elseif(strpos($user_OSagent,"OS/2")) {
            $visitor_os ="OS/2";
        } elseif(strpos($user_OSagent,"PC")) {
            $visitor_os ="Macintosh";
        } elseif(strpos($user_OSagent,"AIX")) {
            $visitor_os ="AIX";
        } elseif(strpos($user_OSagent,"IBM OS/2")) {
            $visitor_os ="IBM OS/2";
        } elseif(strpos($user_OSagent,"BSD")) {
            $visitor_os ="BSD";
        } elseif(strpos($user_OSagent,"NetBSD")) {
            $visitor_os ="NetBSD";
        } else {
            $visitor_os ="其它操作系统";
        }
        return $visitor_os;
    }


    public static function token_create($length = 32)
    {
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        $key = '';
        for ($i = 0; $i < $length; $i++) {
            $key .= $pattern{mt_rand(0, 61)};    //生成php随机数
        }
        return $key;
    }


    public static function is_weixin(){
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
        }
        return false;
    }


    public static function arr_sort($array,$key,$order="asc"){//asc是升序 desc是降序
        $arr_nums=$arr=array();
        foreach($array as $k=>$v){
            $arr_nums[$k]=$v[$key];
        }
        if($order=='asc'){
            asort($arr_nums);
        }else{
            arsort($arr_nums);
        }
        foreach($arr_nums as $k=>$v){
            $arr[count($arr_nums) -1 - $k]=$array[$k];
        }
        return $arr;
    }


    public static function dsubstr($string, $length, $suffix = '', $start = 0, $charset = 'utf-8') {
        if($start) {
            $tmp = dsubstr($string, $start);
            $string = substr($string, strlen($tmp));
        }
        $strlen = strlen($string);
        if($strlen <= $length) return $string;
        $string = str_replace(array('&quot;', '&lt;', '&gt;'), array('"', '<', '>'), $string);
        $length = $length - strlen($suffix);
        $str = '';
        if(strtolower($charset) == 'utf-8') {
            $n = $tn = $noc = 0;
            while($n < $strlen)	{
                $t = ord($string{$n});
                if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $tn = 1; $n++; $noc++;
                } elseif(194 <= $t && $t <= 223) {
                    $tn = 2; $n += 2; $noc += 2;
                } elseif(224 <= $t && $t <= 239) {
                    $tn = 3; $n += 3; $noc += 2;
                } elseif(240 <= $t && $t <= 247) {
                    $tn = 4; $n += 4; $noc += 2;
                } elseif(248 <= $t && $t <= 251) {
                    $tn = 5; $n += 5; $noc += 2;
                } elseif($t == 252 || $t == 253) {
                    $tn = 6; $n += 6; $noc += 2;
                } else {
                    $n++;
                }
                if($noc >= $length) break;
            }
            if($noc > $length) $n -= $tn;
            $str = substr($string, 0, $n);
        } else {
            for($i = 0; $i < $length; $i++) {
                $str .= ord($string{$i}) > 127 ? $string{$i}.$string{++$i} : $string{$i};
            }
        }
        $str = str_replace(array('"', '<', '>'), array('&quot;', '&lt;', '&gt;'), $str);
        return $str == $string ? $str : $str.$suffix;
    }

    /**
     * 移除对象为null或者数组为[]，不包括移除空字符串和0
     * @param $array
     */
    public static function removeEmtpyObjectOrArray(&$array)
    {
        foreach($array as $k=>$v)
        {
            if(is_array($v) && !empty($v))
            {
                self::removeEmtpyObjectOrArray($array[$k]);
            }
            else {
                if($v === null || $v === []) {
                    unset($array[$k]);
                }
            }
        }
    }

    public static function json($data, $removeNull = true) {
        header('Content-Type:application/json; charset=utf-8');
        $json_option = 0;
        if($removeNull) {
            self::removeEmtpyObjectOrArray($data);
        }
        $json = json_encode($data, $json_option);
        exit($json);
    }

    public static function price2($price) {
        return sprintf("%.2f",$price);
    }

    public static function thumbToHttps($http, $domain) {
        $thumbUrl = 'http://slb.dahengdian.com';
        return str_replace($thumbUrl,   $domain.'/slb', $http);
    }

    public static function getimgs($str) {
        $reg = '/((http|https):\/\/)+(\w+\.)+(\w+)[\w\/\.\-]*(jpg|gif|png)/';
        $matches = array();
        preg_match_all($reg, $str, $matches);
        foreach ($matches[0] as $value) {
            $data[] = $value;
        }
        return $data;
    }

    public static function getRand($proArr) {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset($proArr);
        return $result;
    }


    /**
     *      把秒数转换为时分秒的格式
     *      @param Int $times 时间，单位 秒
     *      @return String
     */
    public static function secToTime($times, $type = 0){
        $result = '--';
        if ($times>0) {
            $hour = floor($times/3600);
            $minute = floor(($times-3600 * $hour)/60);
            $second = floor((($times-3600 * $hour) - 60 * $minute) % 60);
            if($type == 1) {
                $result = $hour.':'.$minute.':'.$second;
            }
            else if($type == 2) {
                $result = $hour.'小时'.$minute.'分';
            }
            else if($type == 3) {
                $result = ($hour * 60  + $minute * 1).'分';
            }
            else {
                $result = [$hour, $minute];
            }
        }
        return $result;
    }

    /**
     * 将一个数值切成N份
     * @param  int $number    切的数值
     * @param  int $avgNumber 份数
     * @return array
     */
    public static function numberAvg($fromNumber, $toNumber, $avgNumber)
    {
        $avg     = floor(($toNumber - $fromNumber) / $avgNumber);
        //$ceilSum = $avg * $avgNumber;
        $array   = array();
        for($i = 0; $i < $avgNumber; $i++) {
            array_push($array, (int)($fromNumber + $avg * $i));
            /*if($i < ($fromNumber- $toNumber) - $ceilSum) {
                array_push($array, $fromNumber + $avg + 1);
            } else {
                array_push($array, $fromNumber + $avg);
            }*/
        }
        return $array;
    }




    public static function mobileAsterisk($mobile)
    {
        $mobile_asterisk = substr($mobile,0,4)."****".substr($mobile,8,3);
        return $mobile_asterisk;
    }

    public static function bankNumberAsterisk($bankCardNo){
        //截取银行卡号前4位
        $prefix = substr($bankCardNo,0,4);
        //截取银行卡号后4位
        $suffix = substr($bankCardNo,-4,4);

        $maskBankCardNo = $prefix." **** **** **** ".$suffix;


        return $maskBankCardNo;
    }


    public static function num_format($num){
        if(!is_numeric($num)){
            return false;
        }
        $num = explode('.',$num);//把整数和小数分开
        $rl = $num[1];//小数部分的值
        $j = strlen($num[0]) % 3;//整数有多少位
        $sl = substr($num[0], 0, $j);//前面不满三位的数取出来
        $sr = substr($num[0], $j);//后面的满三位的数取出来
        $i = 0;
        while($i <= strlen($sr)){
            $rvalue = $rvalue.','.substr($sr, $i, 3);//三位三位取出再合并，按逗号隔开
            $i = $i + 3;
        }
        $rvalue = $sl.$rvalue;
        $rvalue = substr($rvalue,0,strlen($rvalue)-1);//去掉最后一个逗号
        $rvalue = explode(',',$rvalue);//分解成数组
        if($rvalue[0]==0){
            array_shift($rvalue);//如果第一个元素为0，删除第一个元素
        }
        $rv = $rvalue[0];//前面不满三位的数
        for($i = 1; $i < count($rvalue); $i++){
            $rv = $rv.','.$rvalue[$i];
        }
        if(!empty($rl)){
            $rvalue = $rv.'.'.$rl;//小数不为空，整数和小数合并
        }else{
            $rvalue = $rv;//小数为空，只有整数
        }
        return $rvalue;
    }

    public static function shuffle_assoc($list) {
        if (!is_array($list)) return $list;
        $keys = array_keys($list);
        shuffle($keys);
        $random = array();
        foreach ($keys as $key)
            $random[$key] = $list[$key];
        return $random;
    }


    public static function substr_cut($user_name){
        $strlen = mb_strlen($user_name, 'utf-8');
        $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
        $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
        return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
    }
}